# -*- coding:utf-8 -*-

# @Time  : 2024/3/1 4:05 PM
# @Author: chenyong
# @Email : chenyong@lingxi.ai
# @File  : knowledge_replace.py

import pandas as pd
import os
import shutil

def get_new_knowledge(excel_file):
    df = pd.read_excel(excel_file, keep_default_na=False)
    result = {}
    product_names = df.columns[1:]
    for product in product_names:
        product = product.strip()
        product_dict = {}
        for _, row in df.iterrows():
            clause = row[0]
            clause_detail = row[product]
            product_dict[clause] = clause_detail.strip()
        result[product] = product_dict

    return result


def replace_knowledge(old_path, new_path):
    product_detail = get_new_knowledge("../bot/insurance_planner_gpt/doc/用户问题-答疑解惑.xlsx")
    old_cur_path = os.path.abspath(old_path)
    new_cur_path = os.path.abspath(new_path)
    if not os.path.exists(new_cur_path):
        os.mkdir(new_cur_path)
    writer_product_introduction = open(os.path.join("../bot/insurance_planner_gpt/doc", 'products_introduction.txt'), 'w')
    for old_subdir_name in os.listdir(old_cur_path):
        if '.DS_Store' in old_subdir_name or '.txt' in old_subdir_name:
            continue
        old_subdir_path = os.path.join(old_cur_path, old_subdir_name)
        new_subdir_path = os.path.join(new_cur_path, old_subdir_name)
        if not os.path.exists(new_subdir_path):
            os.mkdir(new_subdir_path)
        for file_name in os.listdir(old_subdir_path):
            old_file_path = os.path.join(old_subdir_path, file_name)
            new_file_path = os.path.join(new_subdir_path, file_name)
            with open(old_file_path, 'r') as f:
                old_contents = f.read().split('\n\n\n\n\n\n\n')
            writer_new = open(new_file_path, 'w')
            product_name = file_name.replace('.txt', '')
            new_contents = old_contents[0] + '\n\n\n\n\n\n\n'
            if product_name in product_detail:
                new_details = product_detail[product_name]
                for question, answer in new_details.items():
                    if answer:
                        if question == "产品简介":
                            writer_product_introduction.write(product_name + '\n' + answer + '\n\n')
                        else:
                            new_contents = new_contents + question + '\n' + answer + '\n\n'
                writer_new.write(new_contents)
            else:
                print(product_name)
            writer_new.close()
    writer_product_introduction.close()
    print("生成新文件结束")
    shutil.rmtree(old_path)
    shutil.copytree(new_path, old_path)
    print("新文件覆盖原文件结束")


if __name__ == "__main__":
    # excel_file = "用户问题-答疑解惑.xlsx"
    # get_new_knowledge(excel_file)
    old_path = "../knowledge_base/raw_data/insurance_knowledge"
    new_path = "../knowledge_base/raw_data/insurance_knowledge_new"
    replace_knowledge(old_path, new_path)

